//配置Axios的全局属性和基础路径
Vue.prototype.$http = axios;
//每次发送axios请求之前都会加上这个基础路径
axios.defaults.baseURL = "http://localhost:8080";


//==axios的【前置拦截器】拦截调用后端的请求====================//
axios.interceptors.request.use(res => {
    let token = localStorage.getItem("token");
    //如果登陆了，并且没有过期
    if (token) {
        //将token的值设置到请求头
        res.headers["token"] = token;
    }
    return res;//固定语法
}, error => {
    Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//===axios的【后置拦截器】处理后台登录拦截的结果====================//
//一定会比回调函数先执行
// 【后端拦截了请求不做跳转处理而是响应JSON数据让前端判断并处理】
axios.interceptors.response.use(res => {
    //后端响应的是没有登录的信息  =>双重校验，防止执行因为后端异常报错的false
    if (false === res.data.success && "noLogin" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转登陆页面
        location.href = "/login.html";
    }else if(false === res.data.success && "timeOut" === res.data.msg){
        //更改jwt方案
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转登陆页面
        location.href = "/login.html";
    }
    return res;//固定语法
}, error => {
    Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//配置静态资源放行：访问login.html
//有，返回索引，第一次出现位置；没有，返回-1
// if(location.href.indexOf("login.html") == -1 && location.href.indexOf("register.html") == -1){
//     let logininfo = localStorage.getItem("logininfo");
//     let token = localStorage.getItem("token");
//     if(!token || !logininfo){
//         //跳转登陆页面
//         location.href="/login.html";
//     }
// }

//=======静态资源拦截器====================//
//拦截后台系统不经过后端的请求
let url = location.href;//获取当前请求
let path = url.substring(url.lastIndexOf("/"));
//如果访问登陆、注册、微信扫码、微信跳转页面-放行
if (path !== "/login.html"
    && path !== "/register.html"
    && path.indexOf("/login.html") == -1
    && path.indexOf("/register.html") == -1
    && path.indexOf("/callback.html") == -1
    && path.indexOf("/binder.html") == -1) {
    let logininfo = localStorage.getItem('logininfo');
    if (!logininfo) {
        location.href = "login.html";
    }
}

//方法：将给定url地址，转换成JSON格式对象
function parseUrlParams2Obj(url) {
    var obj = {};
    //url：callback.html?code=001B&state=1
    let params = url.substring(url.indexOf("?") + 1);//code=001B&state=1
    let paramsArr = params.split("&");//code=001B  state=1
    for(var i=0;i<paramsArr.length;i++){
        let param = paramsArr[i];
        let paramArr = param.split("=");
        obj[paramArr[0]] = paramArr[1];
    }
    return obj;
}

console.log(this.parseUrlParams2Obj("http://bugtracker.itsource.cn/callback.html?code=001BBwFa1JcDLE0lE3Ia1gsYHE2BBwFK&state=1"))